<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests\SettingRequest;

class SettingsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function edit(SettingRequest $request)
    {
        $user = Auth::user();
        if (!file_exists(storage_path("settings/site.json"))) {
            $settings = [
                'title' => '站点标题',
                'kouliang' => '扣量比例',
            ];
            file_put_contents(storage_path("settings/site.json"), json_encode($settings));
        }
        return view('settings.edit', compact('user', 'settings'));
    }

    public function update(SettingRequest $request)
    {
        $settings = $request->validate([
            'title' => 'required|min:2|max:255',
            'kouliang' => [
                'required',
                'numeric',
                function($attribute, $value, $fail) {
                    if ($value > 100) {
                        return $fail('扣量比例最大为 100.');
                    }
                },
            ],
            'short_urls_nums' => [
                'required',
                'numeric',
                'max:20',
            ],
            'price' => [
                'required',
                'numeric'
            ],
            'outtime' => [
                'required',
                'numeric'
            ],
            'sid' => [
                'required',
                'numeric'
            ],
            'cid' => [
                'required',
                'numeric'
            ],
            'mta_appkey' => [
                'required',
                'string'
            ],
            'qq' => [
                'required',
                'numeric'
            ],
            'kouliang_min' => [
                'required',
                'numeric'
            ],
            'lianxi_text' => [
                'required',
                'string'
            ],
            'lianxi_flash' => [
                'required',
                'boolean'
            ]
        ]);
        file_put_contents(storage_path("settings/site.json"), json_encode($settings));
        return redirect()->route('settings.edit')->with('success', '系统配置更新成功！');
    }
}
